package simpleCommunication;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class CommHelper {
	public static void postData() {
	    // Create a new HttpClient and Post Header
	    HttpClient httpclient = new DefaultHttpClient();
	    HttpPost httppost = new HttpPost("http://172.16.48.129/intellifit/test.php");

	    try {
	        
	        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
	        nameValuePairs.add(new BasicNameValuePair("id", "500"));
	        nameValuePairs.add(new BasicNameValuePair("reps", "17"));
	        nameValuePairs.add(new BasicNameValuePair("name", "Martin"));
	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

	        // Execute HTTP Post Request
	        HttpResponse response = httpclient.execute(httppost);
	        String jsonStr = org.apache.http.util.EntityUtils.toString( response.getEntity() );
	        Log.i("MALA", jsonStr);
	        
	        try {
				JSONObject jsonObj = new JSONObject(jsonStr);
				int myId = jsonObj.getInt("id")+100;
				Log.i("MALA", "Resp id + 100: " + myId);
				Log.i("MALA", "Resp reps: "+jsonObj.getInt("reps"));
				Log.i("MALA", "Resp name: " + jsonObj.get("name"));
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	        
	    } catch (ClientProtocolException e) {
	        // TODO Auto-generated catch block
	    } catch (IOException e) {
	        // TODO Auto-generated catch block
	    }
	} 
	
	
	public static void postDataThread() {
		Thread thread = new Thread(new Runnable(){
		    @Override
		    public void run() {
		        postData();
		    }
		});

		thread.start(); 
	}
}
		
		

